/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shuyihui.rxhttp.subsciber

import android.content.Context
import com.shuyihui.rxhttp.exception.ApiException
import com.shuyihui.rxhttp.exception.ApiException.Companion.handleException
import com.shuyihui.rxhttp.utils.HttpLog
import com.shuyihui.rxhttp.utils.Utils
import io.reactivex.observers.DisposableObserver
import java.lang.ref.WeakReference

/**
 *
 * 描述：订阅的基类
 * 1.可以防止内存泄露。<br></br>
 * 2.在onStart()没有网络时直接onCompleted();<br></br>
 * 3.统一处理了异常<br></br>
 */
abstract class BaseSubscriber<T> : DisposableObserver<T> {
    var contextWeakReference: WeakReference<Context?>? = null

    constructor() {}

    override fun onStart() {
        HttpLog.e("-->http is onStart")
        if (contextWeakReference != null && contextWeakReference!!.get() != null && !contextWeakReference!!.get()?.let {
                Utils.isNetworkAvailable(
                    it
                )
            }!!
        ) {
            //Toast.makeText(context, "无网络，读取缓存数据", Toast.LENGTH_SHORT).show();
            onComplete()
        }
    }

    constructor(context: Context?) {
        if (context != null) {
            contextWeakReference = WeakReference(context)
        }
    }

    override fun onNext(t: T) {
        HttpLog.e("-->http is onNext")
    }

    override fun onError(e: Throwable) {
        HttpLog.e("-->http is onError")
        if (e is ApiException) {
            HttpLog.e("--> e instanceof ApiException err:$e")
            onError(e)
        } else {
            HttpLog.e("--> e !instanceof ApiException err:$e")
            onError(handleException(e))
        }
    }

    override fun onComplete() {
        HttpLog.e("-->http is onComplete")
    }

    abstract fun onError(e: ApiException)
}